package velha.connection.bt;

import java.io.IOException;
import java.io.InterruptedIOException;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import velha.game.Constantes;
import velha.game.Player;
import velha.game.Rival;
import velha.game.VelhaCanvas;

public class BTServidor implements Runnable {

    //Desceve servidor velha
    private static final UUID VELHA_SERVIDOR_UUID = new UUID("F5B0D0E4B0A05A908070605040302010", false);
    //Guarda referencia do Dispositivo Local.
    private LocalDevice localDevice;
    //Aceita conexoes.
    private StreamConnectionNotifier notifier;
    private boolean isClosed = false;
    private final GUIServidor parent;

    public BTServidor(GUIServidor parent) {
        boolean isBTReady = false;
        this.parent = parent;

        try {
            // create/get a local device
            localDevice = LocalDevice.getLocalDevice();

            // set we are discoverable
            if (!localDevice.setDiscoverable(DiscoveryAgent.GIAC)) {
            }

            // prepare a URL to create a notifier
            String url = "btspp://localhost:" + VELHA_SERVIDOR_UUID + ";name=Jogo da Velha";

            // create notifier now
            notifier = (StreamConnectionNotifier) Connector.open(url.toString());

            ServiceRecord sr = localDevice.getRecord(notifier);

            // remember we've reached this point.
            isBTReady = true;
        } catch (IOException e) {
            Alert alerta = new Alert("Erro", "Falha ao inicializar bluetooth", null, AlertType.CONFIRMATION);
            alerta.setTimeout(Alert.FOREVER);
            parent.midlet.getDisplay().setCurrent(alerta, new BTMenu(parent.midlet));
        }

        parent.completeInitialization(isBTReady);

        if (isBTReady) {
            startServer();
        }
    }

    private void startServer() {
        new Thread(this).start();
    }

    public void run() {
        try {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ex) {
                Alert alerta = new Alert("Erro", "Thread interrompida: " + ex, null, AlertType.ERROR);
                alerta.setTimeout(Alert.FOREVER);
                parent.midlet.getDisplay().setCurrent(alerta);
            }

            if (isClosed) {
                return;
            }

            StreamConnection conn = notifier.acceptAndOpen();

            //RemoteDevice ele = RemoteDevice.getRemoteDevice(conn);
            Player jogador = new Player();

            //jogador.nome = localDevice.getFriendlyName();
            jogador.caracter = Constantes.CARACTER_PLAYER_1;
            jogador.isPlayer1 = true;
            jogador.isPrimeiro = true;
            jogador.pontos = 0;

            Rival rival = new Rival();
            //rival.nome = ele.getFriendlyName(true);
            rival.caracter = Constantes.CARACTER_PLAYER_2;
            rival.id = 2;
            rival.pontos = 0;

            VelhaCanvas game = new VelhaCanvas(parent.midlet, jogador, rival);
            game.in = conn.openDataInputStream();
            game.out = conn.openDataOutputStream();

            game.lapis.isVisivel = true;

            parent.midlet.getDisplay().setCurrent(game);

            game.startMessageProcessing();
        } catch (InterruptedIOException iioe) {
            Alert alerta = new Alert("Info", "Cancelado", null, AlertType.CONFIRMATION);
            parent.midlet.getDisplay().setCurrent(alerta, new BTMenu(parent.midlet));
            destroy();
        } catch (IOException ex) {
            Alert alerta = new Alert("Erro", "Problema durante conexao: " + ex, null, AlertType.ERROR);
            alerta.setTimeout(Alert.FOREVER);
            parent.midlet.getDisplay().setCurrent(alerta, new BTMenu(parent.midlet));
            destroy();
        }
    }

    public void destroy() {
        isClosed = true;

        try {
            if (notifier != null) {
                notifier.close();
            }
        } catch (IOException ex) {
            Alert alerta = new Alert("Erro", "Problema ao cancelar: " + ex, null, AlertType.ERROR);
            alerta.setTimeout(Alert.FOREVER);
            parent.midlet.getDisplay().setCurrent(alerta);
        }
    }
}
